package com.hex.ds.hdrs.common.utils;

import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.TriggerBuilder;

import java.text.SimpleDateFormat;
import java.util.Date;

public class CronUtil {

    public static String formatDateByPattern(Date date, String dateFormat){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String formatTimeStr = null;
        if (date != null ) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }

    public static String getCron(Date  date){
        String dateFormat="ss mm HH dd MM ?";
        return formatDateByPattern(date, dateFormat);
    }

    public static CronTrigger getCronTrigger(String cron) {
        if (!CronExpression.isValidExpression(cron)) {
            throw new RuntimeException("cron :" + cron + "表达式解析错误");
        }
        return TriggerBuilder.newTrigger().withIdentity("Caclulate Date").withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
    }

    public static Date getNextTriggerTime(String cron, Date start) {
        CronTrigger trigger = getCronTrigger(cron);
        if (start == null) {
            start = trigger.getStartTime();
        }
        return trigger.getFireTimeAfter(start);
    }

    public static Date getNextTriggerTime(String cron) {
        return getNextTriggerTime(cron, null);
    }

    public static void main(String[] args) {
        String cron = "0 */5 * * * ?";
        Date nextTriggerTime = getNextTriggerTime(cron);
        System.out.println(HdrsDateUtil.format(nextTriggerTime,"yyyy-MM-dd HH:mm:ss"));
    }
}
